package com.atxiao.service.JUC;

/*
* 线程的定制化通信
* */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ShareResource{
    //标志位
    private int flag=1;    //1.AA   2.BB    3.CC

    //创建可重入锁
    private Lock lock=new ReentrantLock();

    //创建三个condition，用来后面对线程的指定唤醒
    private Condition c1=lock.newCondition();
    private Condition c2=lock.newCondition();
    private Condition c3=lock.newCondition();

    //打印5次

    /**
     *
     * @param loop  第几轮
     */
    public void print5(int loop){
        //上锁
        lock.lock();

        try {
            while (flag!=1){
//                c1.wait();
                c1.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+"正在执行："+loop);
            }
            flag=2;
            //唤醒c2线程
            c2.signalAll();
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
            //解锁
                 lock.unlock();
                }

    }


    public void print10(int loop){
        //上锁
        lock.lock();

        try {
            while (flag!=2){
//                c1.wait();
                c2.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+"正在执行："+loop);
            }
            flag=3;
            //唤醒c3线程
            c3.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //解锁
            lock.unlock();
        }

    }

    public void print15(int loop){
        //上锁
        lock.lock();

        try {
            while (flag!=3){
//                c1.wait();
                c3.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+"正在执行："+loop);
            }
            //唤醒c1线程
            flag=1;
            c1.signalAll();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //解锁
            lock.unlock();
        }

    }



}


public class ThreadNotice3 {
    public static void main(String[] args) {


        ShareResource shareResource = new ShareResource();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print5(i+1);
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print10(i+1);
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                shareResource.print15(i+1);
            }
        },"CC").start();

    }



}
